const request = require('../../utils/request')
const config = require('../../config')
const eventBus = require('../../utils/eventBus')

Page({
  data: {
    userInfo: null,
    editInfo: null,
    isEditing: false,
    genderOptions: ['男', '女'],
    selectedGender: 0
  },

  onLoad() {
    this.fetchUserProfile()
  },

  async fetchUserProfile() {
    try {
      // 获取当前用户ID
      const app = getApp();
      if (!app.globalData.isLoggedIn || !app.globalData.userInfo) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        wx.navigateBack();
        return;
      }

      const userId = app.globalData.userInfo.id;
      
      const { data } = await request({
        url: '/api/user/profile',
        data: { userId }
      })

      // 处理头像路径
      if (data.avatar && !data.avatar.startsWith('http')) {
        data.avatar = `${config.development.baseURL}${data.avatar}`
      }

      this.setData({ 
        userInfo: data,
        editInfo: { ...data }
      })
    } catch (error) {
      console.error('获取用户信息失败:', error)
      wx.showToast({
        title: '获取用户信息失败',
        icon: 'none'
      })
    }
  },

  toggleEdit() {
    if (this.data.isEditing) {
      // 取消编辑，恢复原数据
      this.setData({
        editInfo: { ...this.data.userInfo },
        isEditing: false
      })
    } else {
      this.setData({ isEditing: true })
    }
  },

  onInputChange(e) {
    const { field } = e.currentTarget.dataset
    this.setData({
      [`editInfo.${field}`]: e.detail.value
    })
  },

  onGenderChange(e) {
    const index = e.detail.value
    this.setData({
      'editInfo.gender': this.data.genderOptions[index],
      selectedGender: index
    })
  },

  async saveChanges() {
    const { editInfo } = this.data
    
    // 获取当前用户ID
    const app = getApp();
    const userId = app.globalData.userInfo?.id;
    if (!userId) {
      wx.showToast({
        title: '登录状态异常',
        icon: 'none'
      });
      return;
    }

    try {
      await request({
        url: '/api/user/profile',
        method: 'PUT',
        data: {
          ...editInfo,
          userId
        }
      })

      wx.showToast({
        title: '保存成功',
        icon: 'success'
      })

      this.setData({
        userInfo: { ...editInfo },
        isEditing: false
      })

      // 使用eventBus发送更新事件
      eventBus.emit('userInfoUpdated')
    } catch (error) {
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      })
    }
  },

  onBack() {
    const pages = getCurrentPages();
    if (pages.length > 1) {
      wx.navigateBack();
    } else {
      // 如果没有上一页，则跳转到个人中心
      wx.switchTab({
        url: '/pages/my/index'
      });
    }
  },

  // 添加更换头像方法
  async changeAvatar() {
    try {
      // 获取当前用户ID
      const app = getApp();
      const userId = app.globalData.userInfo?.id;
      if (!userId) {
        wx.showToast({
          title: '登录状态异常',
          icon: 'none'
        });
        return;
      }
      
      // 选择图片
      const res = await wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      })

      const tempFilePath = res.tempFilePaths[0]

      // 显示上传中的loading
      wx.showLoading({
        title: '上传中...',
        mask: true
      })

      // 上传图片
      const uploadRes = await new Promise((resolve, reject) => {
        wx.uploadFile({
          url: `${config.development.baseURL}/api/user/upload/avatar`,
          filePath: tempFilePath,
          name: 'file',
          formData: { userId }, // 添加用户ID
          success: (res) => {
            try {
              const result = JSON.parse(res.data)
              resolve(result)
            } catch (e) {
              reject(new Error('解析响应数据失败'))
            }
          },
          fail: reject
        })
      })

      wx.hideLoading()

      if (uploadRes.code === 200) {
        // 直接更新当前页面的数据，而不是重新获取用户信息
        this.setData({
          'userInfo.avatar': `${config.development.baseURL}${uploadRes.data.url}`,
          'editInfo.avatar': `${config.development.baseURL}${uploadRes.data.url}`
        })

        // 发送事件通知其他页面更新头像
        eventBus.emit('userAvatarUpdated', {
          avatar: `${config.development.baseURL}${uploadRes.data.url}`
        })

        wx.showToast({
          title: '头像更新成功',
          icon: 'success'
        })
      } else {
        throw new Error(uploadRes.message || '上传失败')
      }
    } catch (error) {
      wx.hideLoading()
      console.error('更换头像失败:', error)
      wx.showToast({
        title: error.message || '更换头像失败',
        icon: 'none'
      })
    }
  }
})